package com.taobao.demo.user.controller;

import com.taobao.demo.common.utils.JwtUtil;
import com.taobao.demo.user.dto.PasswordDTO;
import com.taobao.demo.user.dto.UserInfoDTO;
import com.taobao.demo.user.dto.UserLoginDTO;
import com.taobao.demo.user.dto.UserRegisterDTO;
import com.taobao.demo.user.entity.User;
import com.taobao.demo.user.entity.UserBehavior;
import com.taobao.demo.user.common.Result;
import com.taobao.demo.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

import org.springframework.security.access.prepost.PreAuthorize;

import java.util.List;

/**
 * 类描述：
 * 
 * @author xhy
 * @date 2025/10/16 18:18
 * @version 1.0.0
 */

@RestController
@RequestMapping("/api/user")
@Validated // 开启参数校验
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Resource
    private IUserService userService;

    @Resource
    private JwtUtil jwtUtil;

    /** 用户注册 */
    @PostMapping("/register")
    public Result<?> register(@Validated @RequestBody UserRegisterDTO registerDTO) {
        try {
            boolean success = userService.register(registerDTO);
            return success ? Result.success("注册成功") : Result.fail("注册失败");
        }catch (Exception e){
            log.error("注册失败：{}", e.getMessage());
            return Result.fail(e.getMessage());
        }
    }

    /** 用户登录（返回 JWT 令牌） */
    @PostMapping("/login")
    public Result<String> login(@Validated @RequestBody UserLoginDTO loginDTO, HttpServletRequest request) {
        try {
            String token = userService.login(loginDTO,JwtUtil.getIp(request));
            return Result.success(token);
        }catch (Exception e){
            return Result.fail(e.getMessage());
        }
    }

//    /** 获取当前用户信息（需携带 Token） */
//    @GetMapping("/info")
//    public Result<UserInfoDTO> getUserInfo(@RequestHeader("Authorization") String token) {
//        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
//        UserInfoDTO infoDTO = userService.getUserInfo(userId);
//        return Result.success(infoDTO);
//    }

    /**
     * 获取当前登录用户信息（需登录认证）
     */
    @GetMapping("/info")
    @PreAuthorize("isAuthenticated()") // 必须登录才能访问
    public Result<UserInfoDTO> getUserInfo(HttpServletRequest request) {
        // 从Token中解析用户ID
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtUtil.getUserIdFromToken(token);
        UserInfoDTO infoDTO = userService.getUserInfo(userId);
        return Result.success(infoDTO);
    }

    /** 修改用户信息（需携带 Token） */
    @PutMapping("/update")
    public Result<?> updateUserInfo(
            @RequestHeader("Authorization") String token,
            @Validated @RequestBody UserInfoDTO infoDTO) {
        Long userId = jwtUtil.getUserIdFromToken(token.replace("Bearer ", ""));
        boolean success = userService.updateUserInfo(userId, infoDTO);
        return success ? Result.success("修改成功") : Result.fail("修改失败");
    }



    // ====================== 用户行为接口（需登录认证） ======================
    /**
     * 记录商品点击行为
     */
    @PostMapping("/behavior/click")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> recordClick(
            @NotNull(message = "商品ID不能为空") @RequestParam Long goodsId,
            HttpServletRequest request
    ) {
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtUtil.getUserIdFromToken(token);
        userService.recordClickBehavior(userId, goodsId);
        return Result.success();
    }

    /**
     * 收藏商品
     */
    @PostMapping("/behavior/favoriteGoods")
    @PreAuthorize("isAuthenticated()")
    public Result<Boolean> favoriteGoods(
            @NotNull(message = "商品ID不能为空") @RequestParam Long goodsId,
            HttpServletRequest request
    ) {
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtUtil.getUserIdFromToken(token);
        boolean success = userService.recordFavoriteBehavior(userId, goodsId);
        return success ? Result.success(true) : Result.fail("已收藏该商品");
    }

    /**
     * 取消收藏商品
     */
    @DeleteMapping("/behavior/cancelFavorite")
    @PreAuthorize("isAuthenticated()")
    public Result<Boolean> cancelFavorite(
            @NotNull(message = "商品ID不能为空") @RequestParam Long goodsId,
            HttpServletRequest request
    ) {
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtUtil.getUserIdFromToken(token);
        boolean success = userService.cancelFavoriteBehavior(userId, goodsId);
        return success ? Result.success(true) : Result.fail("未收藏该商品");
    }

    /**
     * 查询当前用户的行为记录（供推荐服务调用，也可前端展示）
     */
    @GetMapping("/behavior/list")
    @PreAuthorize("isAuthenticated()")
    public Result<List<UserBehavior>> getUserBehaviorList(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtUtil.getUserIdFromToken(token);
        List<UserBehavior> behaviors = userService.getUserBehaviors(userId);
        return Result.success(behaviors);
    }

    // ====================== 管理员接口（需ADMIN/SUPER_ADMIN角色） ======================
    /**
     * 管理员查询所有用户列表（仅ADMIN/SUPER_ADMIN可访问）
     */
    @GetMapping("/admin/list")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPER_ADMIN')")
    public Result<List<User>> listAllUsers() {
        List<User> userList = userService.list();
        return Result.success(userList);
    }

    /**
     * 超级管理员修改用户角色（仅SUPER_ADMIN可访问）
     */
    @PutMapping("/admin/role")
    @PreAuthorize("hasRole('SUPER_ADMIN')")
    public Result<Boolean> updateUserRole(
            @NotNull(message = "用户ID不能为空") @RequestParam Long userId,
            @NotBlank(message = "角色不能为空") @RequestParam String newRole
    ) {
        boolean success = userService.updateUserRole(userId, newRole);
        return success ? Result.success(true) : Result.fail("修改角色失败");
    }


    /**
     * 修改个人密码（需登录）
     */
    @PutMapping("/password")
    @PreAuthorize("isAuthenticated()")
    public Result<Boolean> changePassword(
            @Validated @RequestBody PasswordDTO passwordDTO,
            HttpServletRequest request
    ) {
        String token = request.getHeader("Authorization").substring(7);
        Long userId = jwtUtil.getUserIdFromToken(token);
        boolean success = userService.changePassword(userId, passwordDTO);
        return success ? Result.success(true) : Result.fail("密码修改失败");
    }

    /**
     * 管理员创建商家账号（仅ADMIN/SUPER_ADMIN）
     */
    @PostMapping("/admin/merchant")
    @PreAuthorize("hasAnyRole('ADMIN', 'SUPER_ADMIN')")
    public Result<Boolean> createMerchant(@Validated @RequestBody UserRegisterDTO registerDTO) {
        boolean success = userService.createMerchant(registerDTO);
        return success ? Result.success(true) : Result.fail("创建商家账号失败");
    }
}


